using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Linq;

using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using ProvinceName;
using System.Runtime.Serialization.Json;
using RootobjectName;

namespace weather4
{
    
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        Province py = new Province();
        Dictionary dy = new Dictionary();
        string cid = "";
        string key = Properties.Resources.key;
        T deserializejson<T>(String s)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
            byte[] buf = Encoding.UTF8.GetBytes(s);
            MemoryStream ms = new MemoryStream(buf);
            T obj = (T)json.ReadObject(ms);
            return obj;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                py.getZones();
                dy.getIcons();
                //绑定省份列表到cbProvince控件 
                cbProvince.ItemsSource = py.zones.provinces.Select(x => x.province);
                //λ（兰姆达）演算x => x.ID 称为Lambda表达式,它的意思是查找list数组，将其中的x.ID 查找出来，=>坐标列出了需要的参数x,右边定义了赋予变量x的方法的实现代码，即x.ID
            }
            catch (Exception exp)
            {
                tbZone.Text = exp.Message;
            }
        }
        public class GZipWebClient : WebClient
        {
            protected override WebRequest GetWebRequest(Uri address)
            {
                HttpWebRequest webrequest = (HttpWebRequest)base.GetWebRequest(address);
                webrequest.AutomaticDecompression = DecompressionMethods.GZip |DecompressionMethods.Deflate;
                return webrequest;
            }
        }
        public void clientGzip(string url, string u, string city, string key)
        {
            GZipWebClient client = new GZipWebClient();
            client.Encoding = Encoding.GetEncoding("GB2312");
            client.DownloadDataCompleted += Client_DownloadDataCompleted;
            String urla = url + u + "?location=" + city + "&key=" + key;
            Uri uri = new Uri(urla, UriKind.Absolute);
            client.DownloadDataAsync(uri, city);
        }
        private void Client_DownloadDataCompleted(object sender,DownloadDataCompletedEventArgs e)
        {
            MemoryStream ms = new MemoryStream(e.Result);
            string s = Encoding.UTF8.GetString(e.Result);
            Rootobject w = deserializejson<Rootobject>(s);
            dy.getWeatherItem(w);
            if (s.Contains("now"))
            {
                //绑定now现在天气数据控件 
                firstWeather.DataContext = w.now;
            }
            if (s.Contains("daily"))
            {
                //绑定forecast3-10天天气预报 
                secondWeather.DataContext = w.daily[0];
                thirdWeather.DataContext = w.daily[1];
                fourthWeather.DataContext = w.daily[2];
            }
            if (s.Contains("location"))
            {
                //获取第一个id
                cid = w.FirstLocationId;
                if (cid != null)
                {
                    clientGzip("https://devapi.qweather.com/v7/weather/", "now", cid, key);
                    clientGzip("https://devapi.qweather.com/v7/weather/", "3d", cid, key);
                }
            }
            cbProvince.IsEnabled = true;
            lsCities.IsEnabled = true;
            tbZone.Text = "";
        }

        private void cbProvince_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //省份变化时重新绑定城市列表到lsCities控件 
            if (cbProvince.SelectedIndex >= 0)
            {
                lsCities.ItemsSource = null;
                lsCities.ItemsSource = py.zones.provinces[cbProvince.SelectedIndex].cities;
            }
            else
            {
                lsCities.ItemsSource = null;
            }
        }

        private void lsCities_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //选择城市 
            if (lsCities.SelectedIndex >= 0)
            {
                cbProvince.IsEnabled = false;
                lsCities.IsEnabled = false;
                try
                {
                    String city = lsCities.SelectedItem.ToString();
                    clientGzip("https://geoapi.qweather.com/v2/city/", "lookup", city, key);
                    tbZone.Text = "等待服务器响应...";
                }
                catch (Exception exp)
                {
                    tbZone.Text = exp.Message;
                }
                lsCities.ItemsSource = py.zones.provinces[cbProvince.SelectedIndex].cities;
            }
            else
            {
                lsCities.ItemsSource = null;
            }
        }


    }

    //省类 
    public class ProvinceClass
    {
        public String province { get; set; }
        public List<String> cities { get; set; }
    }
    public class ZoneClass
    {
        public List<ProvinceClass> provinces { get; set; }
    }
    public class Dictionary
    {
        Dictionary<String, String> icons;
        //天气图标 
        public void getIcons()
        {
            icons = new Dictionary<String, String>();
            icons.Add("晴", "a_0.png");
            icons.Add("多云", "a_1.png");
            icons.Add("阴", "a_2.png");
            icons.Add("阵雨", "a_3.png");
            icons.Add("雷阵雨", "a_4.gif");
            icons.Add("雷阵雨并伴有冰雹", "a_5.gif"); 
            
            icons.Add("强沙尘暴", "a_31.gif");
            icons.Add("没有数据", "a_nothing.gif");
        }
        public void getWeatherItem(Rootobject w)
        {
            if (w.now != null)
            {
                KeyValuePair<String, String> obj = icons.FirstOrDefault(x =>x.Key.IndexOf(w.now.text) >= 0 || w.now.text.IndexOf(x.Key) >= 0);
                if (!obj.Equals(null))
                {
                    w.now.icon = "icon\\" + obj.Value;
                }
                else
                {
                    w.now.icon = null;
                }
                w.now.text = "天气状况：" + w.now.text;
                w.now.temp = "现在温度：" + w.now.temp;
            }
            if (w.daily != null)
            {
                foreach (Daily df in w.daily)
                {
                    KeyValuePair<String, String> objdf = icons.FirstOrDefault(x =>x.Key.IndexOf(df.textDay) >= 0 || df.textDay.IndexOf(x.Key) >= 0);
                    if (!objdf.Equals(null))
                    {
                        df.iconDay = "icon\\" + objdf.Value;
                    }
                    else
                    {
                        df.iconDay = null;
                    }
                    df.textDay = "天气状况：" + df.textDay;
                    df.tmp1 = "温度：" + df.tempMin + "-" + df.tempMax;
                }
            }
        }
    }
}
